using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    [SerializeField] private GameObject pauseScreen;
    public int lives { get; private set; }

    [SerializeField] private LivesUIController livesUI;

    [SerializeField] private GameObject gameOverScreen;

    private int score;
    [SerializeField] private TextMeshProUGUI scoreText;

    [SerializeField] private PlayerController player;

    public bool isPaused { get; private set; }
    public bool isGameActive { get; private set; }


    private void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();

        lives = 3;
        livesUI.UpdateLives(lives);
        score = 0;
        scoreText.text = score.ToString();
        isPaused = false;
        isGameActive = true;
    }

    public void PauseGame()
    {
        isPaused = true;
        pauseScreen.SetActive(true);
        Time.timeScale = 0;
    }

    public void UnPauseGame()
    {
        isPaused = false;
        pauseScreen.SetActive(false);
        Time.timeScale = 1;
    }

    public void RemoveLife(int livesToRemove)
    {
        lives -= livesToRemove;
        livesUI.UpdateLives(lives);
        if (lives <= 0)
            GameOver();
    }

    public void AddLife(int livesToAdd)
    {
        lives += livesToAdd;
        if (lives > 5)
            lives = 5;
        livesUI.UpdateLives(lives);
    }

    private void GameOver()
    {
        isGameActive = false;
        StartCoroutine(WaitForDeath());
    }

    private IEnumerator WaitForDeath()
    {
        yield return new WaitForSeconds(2f);
        gameOverScreen.SetActive(true);
    }

    public void AddScore(int scoreToAdd)
    {
        score += scoreToAdd;
        scoreText.text = score.ToString();
    }

    public void RestartGame()
    {
        SceneManager.LoadScene(1);
    }

    public void Quit()
    {
#if UNITY_EDITOR
        EditorApplication.ExitPlaymode();
#else
        Application.Quit();
#endif
    }
}